//
//  YZLSearchAllView.m
//  Car
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 岳明. All rights reserved.
//

#import "YZLSearchAllView.h"
#import "Macro.h"
#import "HTTPTOOL.h"

//Model
#import "YZLSearchModel.h"
#import "YZLSubBrandListModel.h"
#import "YZLNewsModel.h"
#import "YZLPostModel.h"
#import "YZLSeriesListModel.h"
#import "YZLNewsListModel.h"
#import "YZLDiscuss.h"
#import "YZLImageListModel.h"

#import "YZLSubBrandListCell.h"
#import "YZLNewsCell.h"
#import "YZLPostCell.h"
#import "YZImageListCell.h"
#import "YZLHeaderView.h"

@interface YZLSearchAllView () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *searchArray;
@property (nonatomic, strong) NSMutableArray *keyArray;
@property (nonatomic, strong) NSMutableDictionary *rowDic;
@property (nonatomic, strong) UITableView *tableView; /**< 搜索的内容 */
@property (nonatomic, strong) NSArray *imageListArray;
@property (nonatomic, strong) UIImageView *searchingImageView; /**< 搜索中 */
@property (nonatomic, strong) UIImageView *searchNullImageView; /**< 空的 */

@end

@implementation YZLSearchAllView
//1
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.tableView = [[UITableView alloc] init];
        [self addSubview:self.tableView];
        
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        
        [self.tableView registerClass:[YZLSubBrandListCell class] forCellReuseIdentifier:@"SubBrandListReuse"];
        [self.tableView registerClass:[YZLNewsCell class] forCellReuseIdentifier:@"newsReuse"];
        [self.tableView registerClass:[YZLPostCell class] forCellReuseIdentifier:@"postReuse"];
        [self.tableView registerClass:[YZImageListCell class] forCellReuseIdentifier:@"imageReuse"];
        
        self.searchingImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searching"]];
        [self addSubview:self.searchingImageView];
        self.searchingImageView.frame = CGRectMake(0, 0, kWidth, kHeight - 117);

    }
    return self;
}
//2
- (void)layoutSubviews {
    [super layoutSubviews];
//    self.autoresizesSubviews = NO;
    self.tableView.frame = CGRectMake(0, 0, kWidth, kHeight - 117);
    
    


}
//3
- (void)setBodyString:(NSString *)bodyString {
    if (_bodyString != bodyString) {
        _bodyString = bodyString;
    }
    [self handleWithBodyString:bodyString];
    
}
//4
#pragma mark - 数据解析
- (void)handleWithBodyString:(NSString *)bodyString {
    // 汉字转码
    NSString *transcodingString = [bodyString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 判断是否为文章或帖子
    NSString *str = [NSString stringWithFormat:@"searchContent=%@&", transcodingString];
  
    // 数据解析
    [HTTPTOOL POSTWithURL:searchAll body:str bodyStyle:stringStyle httpHead:nil responseStyle:JSON success:^(id result) {
        [self.searchNullImageView removeFromSuperview];
        self.searchArray = [NSMutableArray array];
        self.keyArray = [NSMutableArray array];
        // 将主体字典设为 Model
        YZLSearchModel *searchModel = [YZLSearchModel yzlSearchModelWithDic:result];
        
        // 取出车系数据，如果存在设为 Model
        NSArray *subBLArray = [result objectForKey:@"subBrandList"];
        if ([searchModel.resultType integerValue] == 2) {
            NSMutableArray *mSubBLArray = [NSMutableArray array];
            for (NSDictionary *dic in subBLArray) {
                YZLSubBrandListModel *model = [YZLSubBrandListModel yzlSubBrandListModelWithDic:dic];
                NSArray *seriesListArray = [dic objectForKey:@"seriesList"];
                NSMutableArray *mSeriesListArray = [NSMutableArray array];
                // 具体车型
                for (NSDictionary *dic in seriesListArray) {
                    YZLSeriesListModel *model = [YZLSeriesListModel yzlSeriesListModelWithDic:dic];
                    [mSeriesListArray addObject:model];
                }
                [self.keyArray addObject:[[model.subBrandName stringByReplacingOccurrencesOfString:@"<font color=\"red\">" withString:@""] stringByReplacingOccurrencesOfString:@"</font>" withString:@""]];
                model.seriesList = mSeriesListArray;
                [mSubBLArray addObject:model];
            }
            searchModel.subBrandList = mSubBLArray;
        }
        
        // 取出车型数据，判断是否存在
        NSArray *seriesListArray = [result objectForKey:@"seriesList"];
        if ([searchModel.resultType integerValue] == 1) {
            NSMutableArray *mSeriesListArray = [NSMutableArray array];
            for (NSDictionary *dic in seriesListArray) {
                YZLSeriesListModel *model = [YZLSeriesListModel yzlSeriesListModelWithDic:dic];
                self.imageListArray = [dic objectForKey:@"imageList"];
                NSMutableArray *mImageListArray = [NSMutableArray array];
                // 图片信息
                for (NSDictionary *dic in self.imageListArray) {
                    YZLImageListModel *model = [YZLImageListModel yzlImageListModelWithDic:dic];
                    [mImageListArray addObject:model];
                }
                [self.keyArray addObject:[NSString stringWithFormat:@"%@ 图片", bodyString]];
                model.imageList = mImageListArray;
                [mSeriesListArray addObject:model];
            }
            searchModel.seriesList = mSeriesListArray;
        }
        
        // 取出新闻信息
        NSDictionary *newDic = [result objectForKey:@"news"];
        
        YZLNewsModel *newsModel = [YZLNewsModel yzlNewsModelWithDic:newDic];
        NSArray *newsListArray = [newDic objectForKey:@"newsList"];
        if (newsListArray.count != 0) {
            NSMutableArray *mNewsListArray = [NSMutableArray array];
            // 新闻具体内容
            for (NSDictionary *dic in newsListArray) {
                YZLNewsListModel *model = [YZLNewsListModel yzlNewsListModelWithDic:dic];
                [mNewsListArray addObject:model];
            }
            [self.keyArray addObject:[NSString stringWithFormat:@"%@ 资讯文章", bodyString]];
            newsModel.newsList = mNewsListArray;
            searchModel.news = [NSDictionary dictionaryWithObject:newsModel forKey:@"news"];
        }
        
        // 帖子信息
        NSDictionary *postDic = [result objectForKey:@"post"];
        YZLPostModel *postModel = [YZLPostModel yzlPostModelWithDic:postDic];
        NSArray *postListArray = [postDic objectForKey:@"postList"];
        if (postListArray.count != 0) {
            NSMutableArray *mPostListArray = [NSMutableArray array];
            // 帖子具体内容
            for (NSDictionary *dic in postListArray) {
                YZLDiscuss *model = [YZLDiscuss DiscussWithDictionary:dic];
                [mPostListArray addObject:model];
            }
            postModel.postList = mPostListArray;
            searchModel.post = [NSDictionary dictionaryWithObject:postModel forKey:@"post"];
            [self.keyArray addObject:[NSString stringWithFormat:@"%@ 相关贴子", bodyString]];
        }
        [self.searchArray addObject:searchModel];
        [_tableView reloadData];
        [self createTableViewHeader];
        [self.searchingImageView removeFromSuperview];
        if ( searchModel.subBrandList.count == 0 && searchModel.seriesList.count == 0 && newsModel.newsList.count == 0 && postModel.postList.count == 0) {
            self.searchNullImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchNull"]];
            [self addSubview:self.searchNullImageView];
            self.searchNullImageView.frame = CGRectMake(0, 0, kWidth, kHeight - 117);
        }
    } fail:^(NSError *error) {
        NSLog(@"没搜索到");
    }];
    
}

#pragma mark - tableViewHeader
- (void)createTableViewHeader {
    YZLSearchModel *searchModel = [self.searchArray lastObject];
    if ([searchModel.resultType integerValue] == 1) {
        YZLSeriesListModel *slModel = [searchModel.seriesList objectAtIndex:0];
        YZLHeaderView *headerView = [[YZLHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 75)];
        headerView.model = slModel;
        self.tableView.tableHeaderView = headerView;
        
        headerView.searchString = self.bodyString;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableHeaderViewTap:)];
        [headerView addGestureRecognizer:tap];

    }
}

#pragma mark - tableViewHeaderView 点击事件
- (void)tableHeaderViewTap:(UIGestureRecognizer *)tap {
    
    YZLSearchModel *searchModel = [self.searchArray lastObject];
    YZLSeriesListModel *model = [searchModel.seriesList firstObject];
    [self.delegate tableViewHeaderPuseNextViewControllerWithString:model.seriesId];
}

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    YZLSearchModel *searchModel = [self.searchArray objectAtIndex:0];
    if ([searchModel.resultType integerValue] == 1 && section == 0) {
        return 1;
    } else if ([searchModel.resultType integerValue] == 2 && section < searchModel.subBrandList.count) {
        YZLSubBrandListModel *subBLModel = [searchModel.subBrandList objectAtIndex:section];
        return subBLModel.seriesList.count;
    } else if (section == self.keyArray.count - 2) {
        YZLNewsModel *newsModel = [searchModel.news objectForKey:@"news"];
        return newsModel.newsList.count;
    } else {
        YZLPostModel *postModel = [searchModel.post objectForKey:@"post"];
        return postModel.postList.count;
    }
}
//6
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView {
    return self.keyArray.count;
}

#pragma mark - 自定义组名
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 30)];
    view.backgroundColor = [UIColor colorWithRed:247 / 255.f green:247 / 255.f blue:247 / 255.f alpha:1];
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectZero]; //
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.frame = CGRectMake(15, 0, kWidth, 30);
    headerLabel.opaque = NO; //
    /* 高亮 */
    NSString *keyStr = [self.keyArray objectAtIndex:section];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:keyStr];
    NSRange range = [keyStr rangeOfString:self.bodyString];
    
    [attributedString setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:17]} range:range];
    headerLabel.attributedText = attributedString;
    [view addSubview:headerLabel];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"A7"]];
    imageView.frame = CGRectMake(0, 0, 5, 30);
    [view addSubview:imageView];
    
    return view;
}


#pragma mark - 组的高度
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.0;
}

//8
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YZLSearchModel *searchModel = [self.searchArray lastObject];
    if ([searchModel.resultType integerValue] == 2 && indexPath.section < searchModel.subBrandList.count) {
        YZLSubBrandListModel *sblModel = [searchModel.subBrandList objectAtIndex:indexPath.section];
        YZLSeriesListModel *slModel = [sblModel.seriesList objectAtIndex:indexPath.row];
        YZLSubBrandListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubBrandListReuse"];
        cell.model = slModel;
        cell.searchString = self.bodyString;
        return cell;
    } else if ([searchModel.resultType integerValue] == 1 && indexPath.section == 0) {
        YZLSeriesListModel *sltModel = [searchModel.seriesList objectAtIndex:0];
        YZImageListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imageReuse"];
        cell.model = sltModel;
        return cell;
        
    }
    if (indexPath.section == self.keyArray.count - 2){
        YZLNewsModel *newsModel = [searchModel.news objectForKey:@"news"];
        YZLNewsListModel *newsListModel = [newsModel.newsList objectAtIndex:indexPath.row];
        YZLNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsReuse"];
        cell.model = newsListModel;
        cell.searchString = self.bodyString;
        cell.isAll = YES;
        return cell;
    } else {
        YZLPostModel *postModel = [searchModel.post objectForKey:@"post"];
        YZLDiscuss *discussModel = [postModel.postList objectAtIndex:indexPath.row];
        YZLPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"postReuse"];
        cell.model = discussModel;
        cell.searchString = self.bodyString;
        cell.isAll = YES;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    YZLSearchModel *searchModel = [self.searchArray lastObject];
    if ([searchModel.resultType integerValue] == 1 && indexPath.section == 0 && indexPath.row == 0) {
        return 75;
    } else return 50;
}

#pragma mark - tabViewCell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.delegate pushNextViewOfSearchAllsWithIndex:indexPath WithModel:[self.searchArray lastObject] withKayArray:self.keyArray];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
